from django.utils.deprecation import MiddlewareMixin
from app import models
from django.shortcuts import HttpResponseRedirect,render
import datetime

class Tracer():
     def __init__(self):
         self.user = None
         self.price_policy = None
         self.project = None

class AuthMiddleware(MiddlewareMixin):

    white_ls = ['/api/v1/login/','/api/v1/login/sms/','/api/v1/register/','/api/v1/login/code/','/api/v1/send/sms/']
    def process_request(self,request):
        next_url = request.path_info
        if next_url not in self.white_ls:
            user_id = request.session.get('user_id',0)
            user_obj = models.User.objects.filter(id=int(user_id)).first()
            if user_obj:
                request.tracer = Tracer()
                request.tracer.user = user_obj
                tran_obj = models.Transaction.objects.filter(user=user_obj,status=2).order_by('-id').first()
                current_date = datetime.datetime.now()
                if tran_obj.end_datetime and tran_obj.end_datetime < current_date:
                    tran_obj = models.Transaction.objects.filter(user=user_obj, status=2, price_policy__category=1).first()
                request.tracer.price_policy = tran_obj.price_policy
            else:
                return HttpResponseRedirect('/api/v1/login/')
        else:
            pass

    def process_view(self,request, view, args, kwargs):
        # 判断URL是否是以manage开头，如果是则判断项目ID是否是我创建 or 参与
        if not request.path_info.startswith('/api/v1/manage/'):
            return
        project_id = kwargs.get('id')
        # 是否是我创建的项目
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            # 是我创建的项目的话，我就让他通过
            request.tracer.project = project_object
            return

        # 是否是我参与的项目
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_object:
            # 是我参与的项目
            request.tracer.project = project_user_object.project
            return

        return HttpResponseRedirect('/api/v1/project/list/')